package com.saris.primego.service.impl;

import com.saris.primego.common.context.BaseContext;
import com.saris.primego.dao.AddressBookRepository;
import com.saris.primego.pojo.entity.AddressBook;
import com.saris.primego.service.AddressBookService;
import jakarta.persistence.criteria.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    private final AddressBookRepository addressBookRepository;
    private final RedisTemplate<String, Object> redisTemplate;

    public AddressBookServiceImpl(AddressBookRepository addressBookRepository, RedisTemplate<String, Object> redisTemplate) {
        this.addressBookRepository = addressBookRepository;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 条件查询
     */
    public List<AddressBook> list(AddressBook addressBook) {
        Long userId = addressBook.getUserId();
        String phone = addressBook.getPhone();
        Integer isDefault = addressBook.getIsDefault();

        // 动态构建查询条件
        Specification<AddressBook> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 当 userId 不为空时，添加 userId 条件
            if (userId != null) {
                predicates.add(cb.equal(root.get("userId"), userId));
            }
            // 当 phone 不为空时，添加 phone 条件
            if (phone != null && !phone.isEmpty()) {
                predicates.add(cb.equal(root.get("phone"), phone));
            }
            // 当 isDefault 不为空时，添加 isDefault 条件
            if (isDefault != null) {
                predicates.add(cb.equal(root.get("isDefault"), isDefault));
            }
            if (predicates.isEmpty()) {
                return cb.conjunction();

            } else {
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };

        return addressBookRepository.findAll(spec);
    }

    /**
     * 新增地址
     */
    @Transactional
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookRepository.save(addressBook);
    }

    /**
     * 根据id查询
     */
    public AddressBook getById(Long id) {
        Optional<AddressBook> addressBookOptional = addressBookRepository.findById(id);
        AddressBook addressBook = addressBookOptional.orElse(null);

        if (addressBook != null) {
            Integer isDefault = addressBook.getIsDefault();
            redisTemplate.opsForValue().set("isDefault", isDefault != null ? isDefault : Integer.valueOf(0));
        }
        //查询返回值包含是否为默认的数据
        return addressBook;
    }

    /**
     * 根据id修改地址
     */
    @Transactional
    public void update(AddressBook addressBook) {
        //但是当修改时，由于前端的原因，没有传过来isDefault和userId.需要暂存，另外修改。isDefault采用redis的方式，采用ThreadLocal无效。
        Integer isDefault = (Integer) redisTemplate.opsForValue().get("isDefault");
        if (isDefault != null) {
            addressBook.setIsDefault(isDefault);
        }
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookRepository.save(addressBook);
    }

    /**
     * 设置默认地址
     */
    @Transactional
    public void setDefault(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        List<AddressBook> addressBooks = addressBookRepository.findByUserId(BaseContext.getCurrentId());
        for (AddressBook address : addressBooks) {
            Integer isDefault = address.getIsDefault();
            if (isDefault != null) {
                if (isDefault == 1) {
                    address.setIsDefault(0);
                    address.setUserId(BaseContext.getCurrentId());
                    addressBookRepository.save(address);
                }
            }
        }

        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        Optional<AddressBook> addressBookOptional = addressBookRepository.findById(addressBook.getId());
        if (addressBookOptional.isPresent()) {
            AddressBook address = addressBookOptional.get();
            address.setIsDefault(1);
            address.setUserId(BaseContext.getCurrentId());
            addressBookRepository.save(address);
        }
    }

    /**
     * 根据id删除地址
     */
    public void deleteById(Long id) {
        addressBookRepository.deleteById(id);
    }

}
